#!/bin/bash

. $LKP_SRC/lib/upload.sh

. $LKP_SRC/lib/job.sh
load_job_vars os result_root

prepare_env()
{
	yum install -y ruby ruby-devel make gcc cmake glibc git
	gem install bundle
	cat <<-EOF >> /root/Gemfile
	source 'https://gems.ruby-china.com'

	gem 'rest-client', '= 2.1.0'
	gem 'bigdecimal', '= 1.3.4'
	gem 'activesupport', '= 6.1.4.7'
	gem 'git', '= 1.8.1'
	EOF
	bundle install --gemfile=/root/Gemfile
}

get_results()
{
	yum install -y tar
	cd $TMP
	cci jobs group_id=${group_id} -f id,job_health,result_root | grep "/result/mugen" | grep -v "$id">> temp.output
	printf "%-40s%-15s%-15s%-15s%-15s\n" "testsuite" "sucess_num" "failed_num" "job_id" "job_health" >> "$TMP/summary.txt"
	while read job_id job_health result_root0
	do
		testsuite=$(echo ${result_root0} | awk -F '/' '{print $7}')
		if [ ${job_health} = "success" ];then
			wget https://api.compass-ci.openeuler.org:20007/${result_root0}/results/results.tar
			if [ $? -ne 0 ];then
				echo "cannot find results.tar in ${job_id}"
				sucess_num="[empty]"
				failed_num="[empty]"
				printf "%-40s%-15s%-15s%-15s%-15s\n" "${testsuite}" "${sucess_num}" "${failed_num}" "${job_id}" "${job_health}" >> "$TMP/summary.txt"
				continue
			fi
		else
			sucess_num="[empty]"
			failed_num="[empty]"
				printf "%-40s%-15s%-15s%-15s%-15s\n" "${testsuite}" "${sucess_num}" "${failed_num}" "${job_id}" "${job_health}" >> "$TMP/summary.txt"
			continue

		fi 
		tar zxf results.tar
		cd results
		cd "$testsuite"
		printf "%-40s%-15s\n" "testcase" "result" >> "$TMP/${testsuite}.txt"
		if [ -d succeed ];then
			sucess_num=$(ls succeed | wc -l)
			for success_testcase in $(ls succeed)
			do
				printf "%-40s%-15s\n" "${success_testcase}" "succeed" >> "$TMP/${testsuite}.txt"
			done
		else
			sucess_num=0
		fi
		if [ -d failed ];then
			failed_num=$(ls failed | wc -l)
			for failed_testcase in $(ls failed)
			do
				printf "%-40s%-15s\n" "${failed_testcase}" "failed" >> "$TMP/${testsuite}.txt"
			done
		else
			failed_num=0
		fi

		printf "%-40s%-15s%-15s%-15s%-15s\n" "${testsuite}" "${sucess_num}" "${failed_num}" "${job_id}" "${job_health}" >> "$TMP/summary.txt"
		cd ../../
		rm -f results.tar
		rm -rf results
	done < temp.output
}


upload_statistic_result()
{
	cd $TMP
	for file in $(ls *.txt)
	do
		upload_one_curl $file ${result_root}/results/
	done
}


prepare_env
get_results
upload_statistic_result

